package com.demo.las.service;

import com.demo.las.entity.AffairCatalog;
import com.demo.las.repository.AffairCatalogRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class AffairCatalogService {

    @Autowired
    private AffairCatalogRepository affairCatalogRepository;

    public List<AffairCatalog> getAllActive() {
        return affairCatalogRepository.findAllActive();
    }

    public List<AffairCatalog> getActiveByCategory(Integer categoryCode) {
        return affairCatalogRepository.findActiveByCategory(categoryCode);
    }

    public AffairCatalog addItem(AffairCatalog item) {
        // 生成统一code（如未传入）
        if (item.getCode() == null || item.getCode().isBlank()) {
            item.setCode(item.getCategoryCode() + "-" + item.getItemCode());
        }

        // 校验唯一
        Optional<AffairCatalog> exists = affairCatalogRepository.findByCode(item.getCode());
        if (exists.isPresent()) {
            throw new IllegalArgumentException("事务编号已存在: " + item.getCode());
        }

        // 基础校验（名称与编码）
        if (item.getCategoryName() == null || item.getCategoryName().isBlank()) {
            throw new IllegalArgumentException("大类名称不能为空");
        }
        if (item.getItemName() == null || item.getItemName().isBlank()) {
            throw new IllegalArgumentException("事务名称不能为空");
        }

        item.setActive(true);
        return affairCatalogRepository.save(item);
    }

    // 新增：按ID查询
    public Optional<AffairCatalog> getById(Long id) {
        return affairCatalogRepository.findById(id);
    }

    // 新增：更新库项
    public AffairCatalog updateItem(AffairCatalog item) {
        if (item.getCode() == null || item.getCode().isBlank()) {
            item.setCode(item.getCategoryCode() + "-" + item.getItemCode());
        }
        Optional<AffairCatalog> exists = affairCatalogRepository.findByCode(item.getCode());
        if (exists.isPresent() && !exists.get().getId().equals(item.getId())) {
            throw new IllegalArgumentException("事务编号已存在: " + item.getCode());
        }
        return affairCatalogRepository.save(item);
    }

    // 新增：删除库项
    public void deleteItem(Long id) {
        affairCatalogRepository.deleteById(id);
    }
}